
package com.trial.area.common.controller;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;

import com.trial.area.common.utils.DateEditor;
import com.trial.area.common.utils.StringEscapeEditor;

/**
 * Controller基类，用于获取request，response，session，每个请求都会调用这个方法
 *
 * @author 朱国军
 * @version 2015年7月22日
 */
public class BaseController {

    protected HttpServletRequest request;

    protected HttpServletResponse response;

    protected HttpSession session;

    /** 请求的完整路径,包含参数 */
    protected String fullPath;

    /** 错误页面 */
    protected final static String ERROR_PAGE = "500";

    @ModelAttribute
    public void setReqAndRes(HttpServletRequest request, HttpServletResponse response) {
        this.request = request;
        this.response = response;
        this.session = request.getSession();

        // 实际访问地址
        StringBuffer url = request.getRequestURL();
        // 项目根路径
        String contextPath = request.getContextPath();

        // 项目访问地址
        String basePath = url.substring(0, url.indexOf(contextPath) + contextPath.length());

        request.setAttribute("path", basePath);
        
        try {
            fullPath = getFullPath();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
    
    @InitBinder
    protected void initDateBinder(ServletRequestDataBinder binder) throws Exception {
        // 对于需要转换为Date类型的属性，使用DateEditor进行处理
        binder.registerCustomEditor(Date.class, new DateEditor());
    }
    
    @InitBinder
    protected void initStringBinder(WebDataBinder binder) throws Exception {
        binder.registerCustomEditor(String.class, new StringEscapeEditor(true, false));
    }

    /**
     * 获取实际访问地址前缀
     *
     * @return
     */
    public String getPath() {
        String path = request.getContextPath();
        int port = request.getServerPort();
        String basePath = "";
        if (port == 80) {
            basePath = request.getScheme() + "://" + request.getServerName() + path;
        } else {
            basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path;
        }
        return basePath;
    }
    
    private String getFullPath() throws UnsupportedEncodingException {
        int port = request.getServerPort();
        String basePath = "";
        if (port == 80) {
            basePath = request.getScheme() + "://" + request.getServerName();
        } else {
            basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
        }

        String fullPath = basePath + request.getRequestURI();
        @SuppressWarnings("unchecked")
        Map<String, String[]> paramMap = request.getParameterMap();
        
        if (paramMap != null && !paramMap.isEmpty()) {
            StringBuffer paramString = new StringBuffer();
            for (String key : paramMap.keySet()) {
                paramString.append(key).append("=").append(URLEncoder.encode(paramMap.get(key)[0], "UTF-8")).append("&");
            }
            fullPath = fullPath + "?" + paramString.toString();
            fullPath = StringUtils.removeEnd(fullPath, "&");
        }
        return fullPath;
    }
}
